<?php

require_once 'authpage.php';

/**
 * Description of PhotoController
 *
 * @author user
 */
class PhotoController extends AuthpageController {

    private $postToWall = '';

    /**
     * Generate form data
     * @return <type>
     */
    private function _generate_form_data() {
        $data = array();

        $categ = new ORM('photo_category');
        $categ = $categ->find_all();

        $access = new ORM('access');
        $access = $access->find_all();

        $data['category'] = $categ;
        $data['access'] = $access;

        return $data;
    }

    /**
     * index
     * @param <type> $category_id
     * @param <type> $page
     */
    public function index($category_id = 0, $page = 1) {
        $view_user = $this->view_user;
        $auth_user = $this->auth_user->user;

        /**
         * FORM UPLOAD
         */
        $data = $this->_generate_form_data();
        $data['action'] = URL::site('photo/add');
        $data['photo_upload'] = TRUE;
        $data['button_name'] = "Upload!";
        $data['inline_tag'] = '';
        $data['tag'] = false;
        $data['photo'] = new ORM('photo');


        /**
         * CATEGORY NAME
         */
        $category = "All";
        if ($category_id != 0) {
            $category = new ORM('photo_category');
            $category->find($category_id);
            $category = $category->name;
        }


        /**
         * CATEGORY LINK
         */
        $get = "";
        if ($view_user->id != $auth_user->id) {
            $get = "?uid=" . $view_user->id;
        }

        $categ = new ORM('photo_category');
        $categ = $categ->find_all();

        $category_link = array();
        $category_link["0$get"]['value'] = "All";

        foreach ($categ as $c) {
            $category_link[$c->id . $get]['value'] = $c->name;
        }

        $category_link["99$get"]["value"] = "Tagged";

        // Set visibility for category link
        $category_link[$category_id . $get]['active'] = true;


        /**
         * GET PHOTO
         */
        $user = $view_user;
        $query = "";
        $tagged_category = FALSE;
        if ($category_id == 99) {
            // Tagged Photo
            $tagged_category = TRUE;
            $query = "
            SELECT *
            FROM `photo_tag`
            JOIN `photo` ON `photo`.`id` = `photo_tag`.`photo_id`
            JOIN `user` ON `user`.`id` = `photo`.`owner`
            JOIN `photo_category` ON `photo_category`.`id` = `photo`.`category_id`
            WHERE `photo_tag`.`user_id` = $user->id";
        } else {
            // Non tagged photo
            $query = "
            SELECT *
            FROM `photo`
            JOIN `user` ON `user`.`id` = `photo`.`owner`
            JOIN `photo_category` ON `photo_category`.`id` = `photo`.`category_id`
            ";
            $where = " WHERE `user`.`id` = $user->id";
            if ($category_id != 0) {
                $where .= " AND `category_id` = '$category_id'";
            }
            $query .= $where;
        }
        $photos = DBQuery::instance()->query($query);


        /*
         *  FILTER PHOTO
         */
        $followings = new ORM('followings');
        $followings->where("`followee` = '$view_user->id' AND `follower` = '$auth_user->id'")->find();

        $filter = array();
        if ($view_user->id != $auth_user->id) {
            foreach ($photos as $p) {
                if ($p['photo']['view_access'] <= 2) {
                    $filter[] = $p;
                } else if ($p['photo']['view_access'] == 3) {
                    if ($followings->id != null) {
                        $filter[] = $p;
                    }
                }
            }

            $photos = $filter;
        }


        /**
         * PHOTO PAGINATION
         */
        $number_per_page = 6;
        $offset = ($page - 1) * $number_per_page;

        $num_photos = count($photos);
        $max_page = ceil($num_photos / $number_per_page);

        $photos = array_slice($photos, $offset, $number_per_page);


        /**
         * SET VIEW
         */
        $thumbnail = View::factory('photo/thumbnail',
                        array(
                            'photos' => $photos,
                            'page' => $page,
                            'max_page' => $max_page,
                            'category_id' => $category_id,
                            'pagination_url' => "photo/index/",
                            'category_link' => $category_link,
                            'get' => $get,
                            'auth_user' => $auth_user,
                            'tagged_category' => $tagged_category
                ));

        $this->view->content = View::factory('photo/index',
                        array(
                            'thumbnail' => $thumbnail,
                            'form' => View::factory('photo/form', $data),
                ));
        $this->view->content->form->updateFacebook = $this->postToWall;

        if (isset($_POST["ajax"]) && isset($_POST["thumbnail"])) {
            $this->view = new View("ajax");
            $this->view->content = $thumbnail;
            return;
        }

        if (isset($_POST["ajax"])) {
            $temp = $this->view->content;
            $this->view = new View("ajax");
            $this->view->content = $temp;
            return;
        }
    }

    /**
     * Add
     *
     * @return void
     */
    public function add() {
        require_once BASEPATH . 'core/file.php';

        $check = false;
        $photo = null;
        
        if (isset($_POST['add_photo'])) {
            $photo = new ORM('photo');

            /*
             *  Save Photo
             */
            $file = $_FILES["file"];
            $dest = 'public/upload/photo/' . $file['name'];

            if (File::save($file['tmp_name'], $dest)) {
                // Can Save File :)
                $photo->set($_POST);
                $photo->owner = $this->auth_user->user->id;
                $photo->link = $dest;

                if (!$photo->save()) {
                    show_error('Cannot add photo. /photo/add/');
                } else {
                    // Save tag
                    if (isset($_POST["inline_tag"])) {
                        $this->save_tag($_POST["inline_tag"], $photo->id);
                    }
                    $check = true;
                }
            }
        }

        $url = ($photo != null && $photo->id != null) ? "photo/view/$photo->category_id/$photo->id" : "photo";

        if ($check) {
            $this->postToWall = View::factory('photo/updateFacebook');
            $this->postToWall->url = $url;
            $this->view->content = $this->postToWall;
        }
    }

    private function save_tag($inline_tag, $photo_id) {
        $tags = preg_split("/ /", $inline_tag);
        $tags = array_unique($tags, SORT_STRING);
        foreach ($tags as $t) {

            if ($this->auth_user->user->username == $t) {
                $photo_tag = new ORM("photo_tag");
                $photo_tag->photo_id = $photo_id;
                $photo_tag->user_id = $this->auth_user->user->id;

                if (!$photo_tag->save()) {
                    show_error("Cannot add tag. photo id $photo_id user_id " . $user['id'] . mysql_error());
                }
            } else {
                $query = "
                SELECT `username`, `user`.`id`
                FROM `user`
                JOIN `followings` ON `followee` = `user`.`id`
                WHERE `follower` = '" . $this->auth_user->user->id . "'
                AND `username`='$t'";

                $user = DBQuery::instance()->query($query);

                if (isset($user[0]["user"])) {
                    $user = $user[0]["user"];
                    $photo_tag = new ORM("photo_tag");
                    $photo_tag->photo_id = $photo_id;
                    $photo_tag->user_id = $user["id"];

                    if (!$photo_tag->save()) {
                        show_error("Cannot add tag. photo id $photo_id user_id " . $user['id'] . mysql_error());
                    } else {
                        $auth_user = $this->auth_user->user;

                        $notif = new ORM('notif');
                        $notif->receiver_id = $photo_tag->user_id;
                        $notif->time_stamp = time();
                        $notif->unread = 1;

                        $content = "<a href=\"" . URL::site("profile?uid=$auth_user->id") . "\">$auth_user->username</a>";
                        $content .= " has been tag you on a ";
                        $content .= "<a href=\"" . URL::site("photo/view/0/$photo_id?uid=$auth_user->id") . "\">photo</a>";
                        $notif->content = $content;

                        if (!$notif->save()) {
                            show_error("Cannot add notif tag. photo id $photo_id receiver_id " . $notif->receiver_id . mysql_error());
                        }
                    }
                }
            }
        }
    }

    private function delete_tag($photo_id) {
        $query = "
            DELETE
            FROM `photo_tag`
            WHERE `photo_id` = '$photo_id'";

        DBQuery::instance()->query($query);
    }

    /**
     * Edit
     * @param <type> $id
     */
    public function edit($id = null) {
        // Find Photo
        $photo = new ORM('photo');
        $photo->find($id);

        if (isset($_POST['add_photo']) && $id != null) {
            // Set Data
            $photo->set($_POST);

            // Save Photo
            if (!$photo->save()) {
                show_error('Cannot edit photo. /photo/edit/' . $id);
            } else {
                // Delete tag
                $this->delete_tag($id);

                // Save tag
                $this->save_tag($_POST['inline_tag'], $id);
            }
        }

        URL::redirect("photo/view/$photo->category_id/$photo->id");
    }

    /**
     * Delete
     * @param <type> $id 
     */
    public function delete($id = null) {
        require_once BASEPATH . 'core/file.php';

        if ($id != null) {
            // Load photo
            $photo = new ORM('photo');
            $photo->find($id);
            $file_name = $photo->link;
            if (!$photo->delete($id)) {
                show_error('Cannot delete photo with id ' . $id);
            } else {
                // Delete Success at DB
                // Now, Delete at storage
                File::delete($file_name);
            }
        }

        URL::redirect('photo');
    }

    /**
     * View
     * @param int $id
     */
    public function view($category_id = 0, $id = 0) {
        $view_user = $this->view_user;
        $auth_user = $this->auth_user->user;
        $content_data = array();
        $content_data['auth_user'] = $auth_user;
        $content_data['view_user'] = $view_user;


        /**
         * GET PHOTO
         */
        $photo = new ORM('photo');
        if ($category_id == 99) {
            // tagged
            $photo->find($id);
        } else {
            // non tagged
            $photo->where("`category_id` = '$category_id'")->find($id);
        }
        $content_data['photo'] = $photo;


        /*
         * VIEW ACCESS
         */
        $content_data['show_form'] = !$this->_is_other_user();

        if ($view_user->id != $auth_user->id) {

            if ($photo->view_access == 4) {
                URL::redirect('profile');
            }

            if ($photo->view_access == 3 && !$this->is_follower($auth_user, $view_user)) {
                URL::redirect('profile');
            }
        } else {
            if ($photo->owner != $auth_user->id) {
                URL::redirect('profile');
            }
        }


        /**
         * GET PARAMETER
         */
        $get = '';
        if (isset($_GET['uid'])) {
            $get = "?uid=" . $_GET['uid'];
        }
        $content_data['get'] = $get;


        /**
         * MARK
         */
        $query = "
            SELECT SUM(`mark`) as `mark`
            FROM `photo_mark`
            WHERE `photo_id`=$id
            GROUP BY `photo_id`";
        $mark = DBQuery::instance()->query($query);
        if (count($mark) > 0) {
            $mark = $mark[0]['']["mark"];
        } else {
            $mark = 0;
        }
        $content_data['mark'] = $mark;


        /**
         * EVALUATOR
         */
        $query = "
            SELECT *
            FROM `photo_mark`
            WHERE `photo_id`=$id
            AND `evaluator_id`=$auth_user->id";
        $evaluator = DBQuery::instance()->query($query);
        $content_data['evaluator'] = $evaluator;


        /**
         * COMMENT
         */
        $query = "
            SELECT *
            FROM `photo_comment`
            JOIN `user` ON `photo_comment`.`sender_id` = `user`.`id`
            LEFT JOIN `photo` ON `photo`.`id` = `user`.`photo_id`
            WHERE `photo_comment`.`photo_id` = $id
            ORDER BY `photo_comment`.`id` ASC";
        $comments = DBQuery::instance()->query($query);
        $content_data['comments'] = $comments;

        $user_profic = new ORM('photo');
        $user_profic->find($auth_user->photo_id);
        $user_profic = $user_profic->link;
        $content_data['user_profic'] = $user_profic;


        /**
         * FORM EDIT
         */
        $form_data = $this->_generate_form_data();
        $form_data['action'] = URL::site('photo/edit/' . $photo->id);
        $form_data['photo_upload'] = FALSE;
        $form_data['photo'] = $photo;
        $form_data['button_name'] = "Edit!";
        $form_data['tag'] = true;

        // tag
        $query = "
            SELECT `user`.`id`, `user`.`username`
            FROM `user`
            JOIN `photo_tag` ON `photo_tag`.`user_id` = `user`.`id`
            WHERE `photo_tag`.`photo_id`=$id";
        $tags = DBQuery::instance()->query($query);
        $form_data['inline_tag'] = "";
        foreach ($tags as $t) {
            $form_data['inline_tag'] .= $t["user"]["username"] . " ";
        }
        $content_data["tags"] = $tags;

        /**
         * NAVIGATION PREV NEXT PHOTO
         */
        $prev = new ORM('photo');
        $prev->order_by(array('id' => 'DESC'))
                ->where("
                    `category_id` = '$category_id'
                    AND `owner` = '$view_user->id'
                    AND `id` < $id")
                ->find();

        $next = new ORM('photo');
        $next->where("
                    `category_id` = '$category_id'
                    AND `owner` = '$view_user->id'
                    AND `id` > $id")
                ->find();

        $content_data["prev"] = $prev;
        $content_data["next"] = $next;


        /**
         *  SET VIEW
         */
        $this->view->content = View::factory('photo/view', $content_data);
        $this->view->content->photo = $photo;
        $this->view->content->form = View::factory('photo/form', $form_data);
        $this->view->content->form->updateFacebook = $this->postToWall;

        if (isset($_POST["ajax"])) {
            $temp = $this->view->content;
            $this->view = new View('ajax');
            $this->view->content = $temp;
            return;
        }
    }

    public function mark($user_id, $photo_id, $mark) {
        $photo_mark = new ORM('photo_mark');
        $photo_mark->where("`evaluator_id`=$user_id AND `photo_id`=$photo_id")->find();
        $photo_mark->mark = $mark;
        $photo_mark->evaluator_id = $user_id;
        $photo_mark->photo_id = $photo_id;
        $photo_mark->save();

        // Find photo
        $photo = new ORM('photo');
        $photo->find($photo_id);

        URL::redirect("photo/view/$photo->category_id/$photo_id");
    }

    public function comment($user_id, $photo_id) {
        if (isset($_POST['content'])) {
            $comment = new ORM('photo_comment');
            $comment->content = $_POST["content"];
            $comment->sender_id = $user_id;
            $comment->photo_id = $photo_id;
            if (!$comment->save()) {
                show_error("Cannot add comment $comment->content in photo id $photo_id form user id $user_id");
            }
        }

        // Find photo
        $photo = new ORM('photo');
        $photo->find($photo_id);

        URL::redirect("photo/view/$photo->category_id/$photo_id");
    }

    public function delete_comment($comment_id, $photo_id) {
        $comment = new ORM('photo_comment');
        $comment->find($comment_id);
        if ($comment->id != null) {
            if (!$comment->delete()) {
                show_error("Cannot delete comment with comment id $comment_id");
            }
        }

        // Find photo
        $photo = new ORM('photo');
        $photo->find($photo_id);

        URL::redirect("photo/view/$photo->category_id/$photo_id");
    }

    /**
     * Set Profile Picture
     * @param <type> $photo_id
     */
    public function set_profic($photo_id) {
        // Get Photo
        $photo = new ORM('photo');
        $photo->find($photo_id);

        // Check photo id
        if ($photo->id == null) {
            URL::redirect('profile');
        }

        // Cek access photo
        // Not yet implemented
        // Edit Profile Picture
        $user = $this->auth_user->user;
        $user->photo_id = $photo_id;

        if ($user->save()) {
            URL::redirect("profile");
        } else {
            echo mysql_error();
            show_error("Cannot set profile picture with photo id $photo_id");
        }
    }

    /**
     * Is user_1 follower of user_2?
     * 
     * @param ORM $user_1
     * @param ORM $user_2
     * @return Boolean
     */
    private function is_follower($user_1, $user_2) {
        $followings = new ORM('followings');
        $followings->where("`follower` = '$user_1->id' AND `followee` = '$user_2->id'")->find();

        if ($followings->id == null) {
            return FALSE;
        }

        return TRUE;
    }

}

?>
